package com.xxx.springboot.config;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.xxx.springboot.interceptor.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 类似web.xml的配置类
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Autowired
    private LoginInterceptor loginInterceptor;

	@Autowired
    private AuthInterceptor authInterceptor;

	@Autowired
    private SystemInterceptor systemInterceptor;
	
	@Resource
	private AutoIdempotentInterceptor autoIdempotentInterceptor;
	
	@Autowired
	private MyInterceptor myInterceptor;
	
	@Autowired
    private TokenInterceptor tokenInterceptor;

	/**
	 * paginationInterceptor
	 * @return
	 */
	@Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
	
    /**
     * spring session 自定义cookie序列化
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        return new CustomCookieSerializer();
    }
    
    /**
     * 自定义拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
		//1.加入的顺序就是拦截器执行的顺序，
		//2.按顺序执行所有拦截器的preHandle
		//3.所有的preHandle 执行完再执行全部postHandle 最后是 afterCompletion
    	registry.addInterceptor(autoIdempotentInterceptor); // 3.幂等性拦截器
        registry.addInterceptor(loginInterceptor).excludePathPatterns("/login");
        registry.addInterceptor(authInterceptor);
        registry.addInterceptor(systemInterceptor);
        registry.addInterceptor(myInterceptor);
        registry.addInterceptor(tokenInterceptor).addPathPatterns("/api/**").excludePathPatterns("/api/token/api_token").excludePathPatterns("/api/ws/**");

        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**").excludePathPatterns("/api/token/api_token").excludePathPatterns("/api/ws/**");
    }

    /**
     * 设置跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
    
    
}
